/**
 * Created  on 2018/8/24.
 */
'use strict';
var router = require('express').Router();
var AV = require('leanengine');
var functionTool = require('../queryFun/functionTool');
var Todo = AV.Object.extend('Todo');
var fs = require('fs');
var multiparty = require('multiparty');
var common = require('../cloud/common');
let moment = require('moment')
let momenttz = require('moment-timezone')
momenttz.locale('zh-cn');
let xlsx = require('node-xlsx')
let uuid = require('node-uuid')
/**
 * 订单列表
 */
router.post("/getOrder", async function (req, res) {
    let userOId=req.currentUser.id;
    var shopInfo = await getShopInfo(userOId)
    let shopOId = shopInfo.shopOId
    // let shopOId=req.body.shopOId
    // shopOId="5b446f5a67f356003a7c7f69";//测试
    console.log("getOrder-shopOId-"+shopOId)
    if(!shopOId||shopOId==""){
        return res.json(common.getReturnArr("参数错误"));
    }
    let page = req.body.pageIndex;
    page = Number(page);
    let num = req.body.pageSize;
    let status = req.body.status;
    let receiver = req.body.receiver;
    let orderCode = req.body.orderCode;
    let buyerUser = req.body.buyerUser;
    let buyerOId = req.body.buyerOId;
    functionTool.shopOrderList2('', '', status, receiver, orderCode, shopOId, buyerUser, buyerOId, page, num, function (error, result) {
        if (!error) {
            res.json(common.getReturnArr("OK", "10000", "商品列表获取成功！", result));
        } else {
            res.json(common.getReturnArr(""));
        }
    })
});
//获取店铺信息
async function getShopInfo(userOId){
  var query = new AV.Query('Shop_shop');
  // query.equalTo("status",'1');
  query.equalTo("userOId",userOId);
  return query.first().then(shopObj=>{
    return {
      shopOId:shopObj.id,
      shopName:shopObj.get('name')
    }
  }).catch(error=>{
    console.log(error)
  })
}

/**
 * 更新收货人信息
 */
router.post('/updateOrderWithReceiveInfo', (req, res) => {
    let orderOId = req.body.orderOId;
    let num = req.body.num;
    let receiver = req.body.receiver;
    let phone = req.body.phone;
    let address = req.body.address;

    if(!orderOId||orderOId==""){
        return res.json(common.getErrArr("参数错误"));
    }
    if(!num||num==""|num==0){
        return res.json(common.getErrArr("参数错误"));
    }
    if(!receiver||receiver==""){
        return res.json(common.getErrArr("参数错误"));
    }
    if(!phone||phone==""){
        return res.json(common.getErrArr("参数错误"));
    }
    if(!address||address==""){
        return res.json(common.getErrArr("参数错误"));
    }
    let query = new AV.Query('Shop_order');
    query.get(orderOId).then(result=>{
        if(!result){
            return  res.json(common.getErrArr("订单不存在"));
        }
        result.set("receiver",receiver)
        result.set("phone",phone)
        result.set("address",address)
        result.save().then(async orderObj=>{
            await updateGoodsNum(orderOId,num)
            res.json(common.getReturnArr("OK", "10000", "", orderObj));
        }).catch(error=>{
            console.log(error)
            res.json(common.getErrArr("修改失败"));
        })

    }).catch(error=>{
        console.log(error)
        res.json(common.getErrArr("订单不存在"));
    })


})

function updateGoodsNum(orderOId,num){
    let query = new AV.Query('Shop_order_goods');
    query.equalTo("orderOId",orderOId);
    return query.first().then(result=>{
        if(!result){
            return  false;
        }
        result.set("num",num)
        return result.save().then(goods=>{
            return  true;
        }).catch(error=>{
            console.log(error)
            return  false;
        })
    }).catch(error=>{
        console.log(error)
        return  false;
    })
}
/**
 * 物流列表
 */
router.post("/logistics", function (req, res) {
    var query = new AV.Query('Dictionary');
    query.equalTo('type', '10');
    query.find().then(result => {
        var arr = [];
        arr.push({
            text:"无需物流",
            value:"-1"
        })
        for (let item of result) {
            let obj = {};
            obj.text = item.get('name');
            obj.value = item.get('code');
            arr.push(obj)
        }
        res.json(common.getReturnArr("OK", "10000", "", arr));
    }).catch(error=>{
        console.log(error);
        res.json(common.getErrArr(""));
    })
});


/**
 * 发货
 */
router.post("/sendGoods", function (req, res) {
    req.params = req.body;
    let orderOId=req.params.orderOId;
    let logisticsComCode = req.params.logisticsComCode;//快递公司代码
    let logisticsCom = req.params.logisticsCom;//物流公司
    let expressCode = req.params.expressCode;//快递编号
    // console.log(req.params)
    if(!orderOId||orderOId==""){
        return res.json(common.getErrArr("参数错误"));
    }
    if(!logisticsComCode||logisticsComCode==""){
        return res.json(common.getErrArr("参数错误"));
    }
    if(!logisticsCom||logisticsCom==""){
        return res.json(common.getErrArr("参数错误"));
    }
    if(!expressCode||expressCode==""){
      if (logisticsComCode == "-1") {
        logisticsCom = "无需物流";
        expressCode = "";
      } else {
        return res.json(common.getErrArr("参数错误"));
      }
    }
    functionTool.doSendGoods(req, function (err, result) {
        if(result==10000){
            res.json(common.getReturnArr("OK", "10000", "", result));
        }else{
            res.json(common.getErrArr(""));
        }

    })
});

router.post('/xlsxUpload', (req, res) => {
    var form = new multiparty.Form();
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log(err)
        } else {
            let path = files.file[0].path

            // if (!xlsxParser.inspectionLogisticsXlsxAvailable(path)) {
            //     let rs = common.getReturnArr("", 10001, "文件格式有问题，请按照提示的格式填写内容", '');
            //     res.json(rs);
            //     return
            // }


            fs.readFile(path, (error, data) => {
                let fileName = path.substring(path.lastIndexOf("/") + 1);
                var file = new AV.File(fileName, data);
                file.save().then(function (fl) {
                    let fileUrl = fl.url()
                    let rs = common.getReturnArr("", 10000, "上传成功", fileUrl);
                    res.json(rs);
                }, (reject) => {
                    console.log(reject);
                    return
                })
            })
        }

    });
})
/**
 * 文件上传之后，开始进行数据的逻辑处理。
 */
router.post('/logisticsUpload', (req, res) => {
    let filePath = req.body.filePath
    let userOId = req.currentUser.id
    functionTool.batchCourierDeliveryXLSX(filePath, userOId, (error,result) => {
        if(!error){
            res.json(common.getReturnArr(10000, 10000, '操作完成', ''))
        }else{
            res.json(common.getErrArr(error))
        }

    })
})

/**
 * 订单导出
 */
router.post('/exportXlsxOrder', async function (req, res) {
    console.log("-------exportXlsxOrder-------");
    let exportStatus = JSON.parse(req.body.exportStatus)
    // let shopOId = req.body.shopOId
    // shopOId="5b446f5a67f356003a7c7f69";//测试
    let userOId=req.currentUser.id;
    var shopInfo = await getShopInfo(userOId)
    let shopOId = shopInfo.shopOId
    if(!shopOId||shopOId==""){
        return res.json(common.getReturnArr("参数错误"));
    }
    console.log("exportStatus="+exportStatus+";shopOId="+shopOId)
    let queryOrder = new AV.Query('Shop_order')
    queryOrder.containedIn('status', exportStatus)
    queryOrder.equalTo('shopOId', shopOId)
    queryOrder.limit(1000)
    queryOrder.descending('orderCode')
    queryOrder.find().then(async results => {
        console.log("exportXlsxOrder="+results.length)
        let array = []
        for (let item of results) {
            let time=""
            if(item.get('payTime')){
                time=new moment(item.get('payTime')).format('YYYY-MM-DD HH:mm:ss').toString()
                time=momenttz.tz(new Date(time), 'Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss').toString()
            }
            let num=await getGoodsNum(item.get("objectId"))
            let obj = {
                goodsName: item.get('goods'),
                orderCode: item.get('orderCode')+"",
                receiver: item.get('receiver'),
                phone: item.get('phone'),
                payTime: time,
                address: item.get('address'),
                num: num

            }
            array.push([obj.goodsName,obj.num, obj.orderCode, obj.receiver, obj.phone, obj.payTime, obj.address])
        }

        //生成excel
        let xlsxTitle =  [['商品名称','购买数量','订单号','收货人','手机号','购买时间','收货地址']]
        try {
            let param = [{
                name: '订单列表',
                data: [...xlsxTitle,...array]

            }]
            let r = JSON.parse(JSON.stringify(param))
            const result = xlsx.build(r);
            let fileUuid = uuid.v4()

            await fs.writeFileSync(`${process.cwd()}/${fileUuid}.xlsx`, result, 'binary')

            let path = `${process.cwd()}/${fileUuid}.xlsx`
            let fileName = `${fileUuid}.xlsx`
            fs.readFile(path, (error, data) => {
                var file = new AV.File(fileName, data);
                file.save().then(function (file) {
                    fs.unlink(path, function () {

                    })
                    res.json(common.getReturnArr(10000, 10000, '获取订单成功', file.url()))
                }).catch(error=>{
                    console.log(error)
                    res.json(common.getErrArr(error.message))
                })
            })
        } catch (error) {
            console.log(error)
            res.json(common.getErrArr('操作失败！'))
        }
    }).catch(error=>{
        console.log(error)
        res.json(common.getErrArr('操作失败！'))
    })
})

function getGoodsNum(orderOId){
    let query = new AV.Query('Shop_order_goods');
    query.equalTo("orderOId",orderOId);
    return query.first().then(result=>{
        if(!result){
            return  false;
        }
        return result.get("num")
    }).catch(error=>{
        console.log(error)
        return  false;
    })
}


module.exports = router;